#include <stdio.h>
#include "common.h"

static struct distance_table dt0;
static int me;

void printdt0(dtptr)
struct distance_table *dtptr;

{
    printf("                via     \n");
    printf("   D0 |    1     2    3 \n");
    printf("  ----|-----------------\n");
    printf("     1|  %3d   %3d   %3d\n",dtptr->costs[1][1],
           dtptr->costs[1][2],dtptr->costs[1][3]);
    printf("dest 2|  %3d   %3d   %3d\n",dtptr->costs[2][1],
           dtptr->costs[2][2],dtptr->costs[2][3]);
    printf("     3|  %3d   %3d   %3d\n",dtptr->costs[3][1],
           dtptr->costs[3][2],dtptr->costs[3][3]);
}


/* students to write the following two routines, and maybe some others */


void rtinit0() 
{
    me = 0;
    printf("Initialize dt%d\n", me);
    for (int i = 0; i < 4; ++i) {
        for (int j = 0; j < 4; ++j) {
            dt0.costs[i][j] = 999;
        }
    }
    dt0.costs[0][1] = 1;
    dt0.costs[0][2] = 3;
    dt0.costs[0][3] = 7;
    dt0.costs[0][0] = 0;
    printTable(&dt0, me);

    send2Neighbors(&dt0, me);
}


void rtupdate0(rcvdpkt)
  struct rtpkt *rcvdpkt;
{
    int src = rcvdpkt->sourceid;
    for (int i = 0; i < 4; ++i) {
        dt0.costs[src][i] = rcvdpkt->mincost[i];
    }
    int needNotify = 0;
    for (int i = 0; i < 4; ++i) {
        if (i == me)
            continue;
        int minDist = 999;  // compute 0 -> i
        for (int j = 0; j < 4; ++j) { // via j
            if (dt0.costs[j][i] == 999) {
                continue;
            }
            minDist = min(minDist, dt0.costs[me][j] + dt0.costs[j][i]);
        }
        if (minDist < dt0.costs[me][i]) {
            dt0.costs[me][i] = minDist;
            // update the Dx(y) to neighbors
            needNotify = 1;
        }
    }

    if (needNotify) {
        printf("dt0 Updated:\n");
        send2Neighbors(&dt0, me);
    }
    printTable(&dt0, me);
}

void linkhandler0(linkid, newcost)
  int linkid, newcost;

/* called when cost from 0 to linkid changes from current value to newcost*/
/* You can leave this routine empty if you're an undergrad. If you want */
/* to use this routine, you'll need to change the value of the LINKCHANGE */
/* constant definition in prog3.c from 0 to 1 */
	
{
}

